<?php defined('SYSPATH') OR die('No direct access allowed.');
/**
 * Default Kohana controller. This controller should NOT be used in production.
 * It is for demonstration purposes only!
 *
 * @package    Core
 * @author     Kohana Team
 * @copyright  (c) 2007-2008 Kohana Team
 * @license    http://kohanaphp.com/license.html
 */
class Post_Controller extends BaseController {
	 
	public function __construct()
	{
		parent::__construct();
	}
	private function ViewPost($threadid = NULL,$read = false)
	{
		$this->template->content = new View('PostList');
		$this->template->title = 'E-study Post List';
		//$posts = ORM::factory('post')->where('pos_thrid', $threadid)->orderby('pos_id', 'asc')->find_all();
		//$thread = ORM::factory('thread')->where('thr_id', $threadid)->orderby('thr_id', 'asc')->find();
		$postall = ORM::factory('post')->where('pos_thrid', $threadid);
		$this->pagination = new Pagination(array('total_items'=>count($postall)));
		$offset = $this->pagination->sql_offset;
		$posts = $postall->find_all($this->limit,$offset);
		//$posts->user = ORM::factory('post')->where('pos_thrid',$threadid)->with('user')->with('post:pos_authorid','user:id')->find_all();
		$postAuthor = ORM::factory('post')->find_all();
		$thread = ORM::factory('thread')->find($threadid);
		if($read)
		{
			$thread->thr_hits += 1;
			$thread->save();
		}
		$this->template->content->replypost = null;
		$this->template->content->threadid = $threadid;
		$this->template->content->postTitle = $thread->thr_subject;
		$this->template->content->posts = $posts;
	}
	public  function PostList($threadid = NULL)
	{
		$this->ViewPost($threadid,true);
	}
	public function ReplyPost($threadid = NULL)
	{
		$this->ViewPost($threadid);
		$this->template->title = 'Add Thread';
		$form = new Forge(url::current());
		$form->input('title')->label(TRUE)->rules('required|length[5,32]')->style('width:200px;');
		$form->Textarea('Content')->label(true)->rules('required|length[5,200]')->cols('80')->rows('5');
		$form->submit('submit');
		$this->template->content->replypost = $form->render();
		if ($form->validate())
		{
			$thread = ORM::factory('thread')->find($threadid);
			$thread->thr_replies +=1;
			$thread->save();
			$post = new post_Model();
			$post->pos_thrid = $threadid;
			$post->pos_id = $threadid;
			$post->pos_author = $this->user->username;
			$post->Author_id = $this->user->id;
			$post->pos_postdate  = date("Y-m-d H:i:s");
			$post->pos_subject = $form->title->value;
			$post->pos_ipfrom  = Ip::get_real_ip();
			$post->pos_content = $form->Content->value;
			$post->save();
			url::redirect('Post/PostList/'.$threadid);
		}
	}

}